<template>
    <div class="trademark-layout">
        <el-card class="box-card">
            <!-- 添加品牌 按钮 -->
            <el-button type="primary" icon="Plus" @click="addTradeMark">
                添加品牌
            </el-button>
            <!-- 表格组件 -->
            <el-table border :data="tradeMarkList">
                <el-table-column
                    label="序号"
                    width="80"
                    align="center"
                    type="index"
                />
                <el-table-column label="品牌名称">
                    <template #="{ row }">
                        <span class="tm-name">{{ row.tmName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{ row }">
                        <img
                            :src="row.logoUrl"
                            alt=""
                            style="width: 100px; height: 100px"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作">
                    <template #="{ row, $index }">
                        <el-button
                            type="warning"
                            icon="Edit"
                            size="small"
                            @click="updateTradeMark(row)"
                        >
                            修改
                        </el-button>
                        <el-popconfirm
                            title="确认删除这个产品吗?"
                            @confirm="deleteTradeMark(row.id)"
                            width="200px"
                        >
                            <template #reference>
                                <el-button
                                    type="danger"
                                    icon="Delete"
                                    size="small"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div class="demo-pagination-block">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    @current-change="getTradeMarkList()"
                    @size-change="getTradeMarkList()"
                    :page-sizes="[10, 20, 30, 40]"
                    layout=" prev, pager, next, jumper,->,total, sizes"
                    :total="total"
                />
            </div>
        </el-card>

        <!-- 对话框组件 -->

        <el-dialog
            v-model="dialogFormVisible"
            :title="TrademarkParams.id ? '修改品牌' : '添加品牌'"
        >
            <el-form
                style="width: 80%"
                :rules="rules"
                :model="TrademarkParams"
                ref="formRef"
            >
                <el-form-item
                    label="品牌名称"
                    label-width="100px"
                    prop="tmName"
                >
                    <el-input
                        autocomplete="off"
                        v-model="TrademarkParams.tmName"
                    />
                </el-form-item>
                <el-form-item
                    label="品牌LOGO"
                    label-width="100px"
                    prop="logoUrl"
                >
                    <el-upload
                        class="avatar-uploader"
                        action="/api/admin/product/fileUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img
                            v-if="TrademarkParams.logoUrl"
                            :src="TrademarkParams.logoUrl"
                            class="avatar"
                        />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button type="primary" @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import {
    reqTradeMark,
    reqAddOrUpdateTradeMark,
    reqDeleteTradeMark,
} from '@/api/product/trademark';
import {
    type Records,
    TrademarkList,
    ResponseData,
    Trademark,
} from '@/api/product/trademark/type';
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
// 定义当前页码
const currentPage = ref<number>(1);
// 定义每页显示的数量
const pageSize = ref<number>(3);
// 定义品牌列表数据
const tradeMarkList = ref<Records>([]);
// 定义品牌数据总数量
const total = ref<number>(0);
// 控制对话框显示与隐藏
const dialogFormVisible = ref(false);
// 定义新增品牌数据
const TrademarkParams = reactive({
    tmName: '',
    logoUrl: '',
});
const formRef = ref();
// 请求品牌列表数据
const getTradeMarkList = async () => {
    const result: TrademarkList = await reqTradeMark(
        currentPage.value,
        pageSize.value,
    );
    if (result.code === 200) {
        tradeMarkList.value = result.data.records;
        total.value = result.data.total;
    }
};
getTradeMarkList();
const init = () => {
    TrademarkParams.tmName = '';
    TrademarkParams.logoUrl = '';
    TrademarkParams.id = 0;
    // formRef.value?.clearValidate('tmName')
    // formRef.value?.clearValidate('logoUrl')
    nextTick(() => {
        formRef.value.clearValidate('tmName');
        formRef.value.clearValidate('logoUrl');
    });
};
const addTradeMark = () => {
    dialogFormVisible.value = true;
    init();
};
const updateTradeMark = (row: Trademark) => {
    dialogFormVisible.value = true;
    Object.assign(TrademarkParams, row);
    formRef.value?.clearValidate('tmName');
    formRef.value?.clearValidate('logoUrl');
};
const deleteTradeMark = async (row: Trademark) => {
    const res = await reqDeleteTradeMark(row);
    console.log('res', res);
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: '删除成功',
        });
        getTradeMarkList();
    } else {
        ElMessage({
            type: 'error',
            message: res.data,
        });
    }
};
const cancel = () => {
    dialogFormVisible.value = false;
};
const confirm = async () => {
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 校验成功
            const res: ResponseData =
                await reqAddOrUpdateTradeMark(TrademarkParams);
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: TrademarkParams.id ? '修改成功' : '添加成功',
                });
                getTradeMarkList();
                dialogFormVisible.value = false;
            } else {
                ElMessage({
                    type: 'error',
                    message: TrademarkParams.id ? '修改失败' : '添加失败',
                });
            }
        } else {
            // 校验失败
            ElMessage({
                type: 'error',
                message: '请填写完整信息',
            });
        }
    });
};
// 上传图片成功触发的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile,
) => {
    TrademarkParams.logoUrl = URL.createObjectURL(uploadFile.raw!);
    //   清除校验结果
    formRef.value.clearValidate('logoUrl');
};
// 上传图片之前触发的钩子 约束文件类型和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (
        rawFile.type == 'image/jpeg' ||
        rawFile.type == 'image/png' ||
        rawFile.type == 'image/gif'
    ) {
        return true;
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('Avatar picture size can not exceed 4MB!');
        return false;
    }
    ElMessage.error('Avatar picture must be JPG format!');
    return false;
};
// 自定义表单校验
const validateTmName = (rule: any, value: any, callback: any) => {
    if (value.trim().length < 2 || value.trim().length > 10) {
        callback(new Error('品牌名称长度在2-10之间'));
    } else {
        callback();
    }
};
const validateLogoUrl = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请上传品牌LOGO'));
    } else {
        callback();
    }
};
const rules = {
    tmName: [
        {
            required: true,
            trigger: 'blur',
            validator: validateTmName,
        },
    ],
    logoUrl: [
        {
            required: true,
            validator: validateLogoUrl,
        },
    ],
};
</script>

<style lang="scss">
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.trademark-layout {
    .el-table {
        margin-top: 10px;
    }
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
